package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import java.util.List;
import java.util.Random;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityAudioEditBinding;
import flc.ast.databinding.ActivityAudioExtractionBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.audio.AudioFormat;
import stark.common.basic.media.audio.AudioPlayerImpl;
import stark.common.basic.media.audio.IAudioPlayer;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.view.container.StkLinearLayout;

public class AudioExtractionActivity extends BaseAc<ActivityAudioExtractionBinding> implements IAudioPlayer.IListener {

    public static String videoPath;
    private String outPath = "";
    protected IAudioPlayer mAudioPlayer;
    private long videoLength;
    private Dialog mySaveDialog;
    private SeekBar seekBar;
    private TextView textView;
    private StkLinearLayout llAudioSaveSuc;


    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvPlayLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mHandler.postDelayed(this, 500);
        }
    };


    @Override
    protected int onCreate() {
        return R.layout.activity_audio_extraction;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        mDataBinding.ivAudioExtractionBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mAudioPlayer = new AudioPlayerImpl();
        mAudioPlayer.setListener(this);
        mDataBinding.ivPlayStart.setOnClickListener(this);
        mDataBinding.ivPlay.setOnClickListener(this);
        mDataBinding.ivAudioExtractionSave.setOnClickListener(this);
        //保存弹框
        saveDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlayStart:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.azantinzhong2);
                    mDataBinding.videoView.pause();
                } else {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.ivPlay:
                if (mAudioPlayer.isPlaying()) {
                    mAudioPlayer.pause();
                    mDataBinding.ivPlay.setImageResource(R.drawable.azantinzhong);
                } else {
                    mAudioPlayer.resume();
                    mDataBinding.ivPlay.setImageResource(R.drawable.abofangzhong2);
                }
                break;
            case R.id.ivAudioExtractionSave://保存
                saveAudio();
                break;
        }
    }

    @Override
    protected void initData() {
        videoLength = MediaUtil.getDuration(videoPath);
        setPlayer();
        audioExt();
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        mDataBinding.tvPlayLeft.setText("00:00");
        mDataBinding.tvPlayRight.setText(" / " + TimeUtil.getMmss(videoLength));
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mDataBinding.tvPlayLeft.setText("00:00");
                mDataBinding.ivPlayStart.setImageResource(R.drawable.azantinzhong2);
                mDataBinding.videoView.seekTo(1);
                stopTime();
            }
        });
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
        mDataBinding.videoView.start();
        startTime();
    }

    //保存音频
    private void saveAudio() {
        seekBar.setVisibility(View.VISIBLE);
        llAudioSaveSuc.setVisibility(View.GONE);
        textView.setText(getString(R.string.audio_save_ing));
        mySaveDialog.show();
        seekBar.setProgress(new Random().nextInt(60));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {
                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //保存
                        FileP2pUtil.copyPrivateAudioToPublic(mContext, outPath);
                        String path = PathUtils.getFilesPathExternalFirst() + Content.myAudio + "/" + FileUtils.getFileName(outPath);
                        FileUtils.move(outPath, path);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String obj) {
                        textView.setText(getString(R.string.pic_save_suc));
                        seekBar.setVisibility(View.GONE);
                        llAudioSaveSuc.setVisibility(View.VISIBLE);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startActivity(HomeActivity.class);
                            }
                        }, 1000);
                    }
                });
            }
        }, 1000);
    }

    private void audioExt() {
        List<AudioFormat> audioFormats = EditorHolder.editor().supportAudioFormat();
        EditorHolder.editor().videoExtractAudio(videoPath, audioFormats.get(0), new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.extract_suc));
                outPath = outFilePath;
                mAudioPlayer.play(outPath);
            }

            @Override
            public void onFailure(String errMsg) {
                dismissDialog();
                ToastUtils.showShort(R.string.extract_def);
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.extract_ing) + progress + getString(R.string.unit_percent));
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAudioPlayer != null) {
            mAudioPlayer.resume();
        }
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
        mDataBinding.videoView.start();
        startTime();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mAudioPlayer != null) {
            mAudioPlayer.pause();
        }
        stopTime();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAudioPlayer != null) {
            mAudioPlayer.stop();
        }
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    public void onUpdatePlayTime(int curPlayTime, int duration) {
        mDataBinding.sbPlay.setMax((int) duration / 1000);
        mDataBinding.sbPlay.setProgress(curPlayTime / 1000);
        mDataBinding.tvPlayLeftText.setText(TimeUtil.getMmss(curPlayTime));
        mDataBinding.tvPlayRightText.setText("/" + TimeUtil.getMmss(duration));
    }

    @Override
    public void onPlayChange(boolean isPlaying) {
        if (isPlaying) {
            mDataBinding.ivPlay.setImageResource(R.drawable.abofangzhong2);
        } else {
            mDataBinding.ivPlay.setImageResource(R.drawable.azantinzhong);
        }
    }

    //保存弹框
    private void saveDialog() {
        mySaveDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_audio_save, null);
        mySaveDialog.setContentView(inflate);
        mySaveDialog.setCancelable(true);
        Window dialogWindow = mySaveDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        seekBar = inflate.findViewById(R.id.sbProgress);
        textView = inflate.findViewById(R.id.tvAudioSaveTitle);
        llAudioSaveSuc = inflate.findViewById(R.id.llAudioSaveSuc);
    }

}